<?php

namespace app\service;

use app\common\BaseService;
use app\model\InnerPurchase as InnerPurchaseModel;
use app\model\InnerPurchaseOrder as InnerPurchaseOrderModel;
use think\facade\Db;

class InnerPurchaseService extends BaseService
{
  public static function getInstance(): InnerPurchaseService
  {
    return parent::getInstance();
  }

  public static function getModel(): InnerPurchaseOrderModel
  {
    return InnerPurchaseOrderModel::getInstance();
  }

  public static function getDetailModel(): InnerPurchaseModel
  {
    return InnerPurchaseModel::getInstance();
  }

  /*
   * 通过condition获取inner_purchaseOrder
   */
  public function getInnerOrderByCondition($conditions, $order = ['id' => 'DESC']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $result = $query->order($order)->select()->toArray();
    return $result;
  }

  /*
   * 关联门店
   */
  public function getInnerOrderJoinBase($conditions = []) {
    $db = Db::name('inner_purchase_order')
      ->alias('o')
      ->field('o.*, u.basename,u.address')
      ->join('user u', 'u.base = o.base', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $db = $db->where($field, $op, $value);
    }
    return $db
      ->order(['o.id' => 'DESC'])
      ->select()
      ->toArray();
  }

  /*
   * 连商品表goods查询inner_purchase信息
   */
  public function getInnerJoinGoods($conditions = []) {
    $conditions[] = ['i.status', 1, '='];
    $db = Db::name('inner_purchase')
      ->alias('i')
      ->field('i.*, o.sell_number,o.base,o.purchase_time,o.operate_time,o.confirm_time,o.comment as message, o.status as status,g.sale_name,g.category_id,g.unit,u.basename,u.address,c.category_name,g. NAME AS good_name, s.count AS rest_count')
      ->join('inner_purchase_order o', 'o.id = i.inner_order_id', 'LEFT')
      ->join('goods g', 'g.id = i.goods_id', 'LEFT')
      ->join('user u', 'u.base = o.base', 'LEFT')
      ->join('store_house s', 'o.base = s.base and s.goods_id = i.goods_id', 'LEFT')
      ->join('category c', 'c.id = g.category_id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $db = $db->where($field, $op, $value);
    }
    return $db
      ->order('i.id', 'DESC')
      ->select()
      ->toArray();
  }

  /*
   * 门店内部采购更新
   */
  public static function updateMultiInner($oid, $purchase, $data, $type) {
    $order = InnerPurchaseService::getModel()
      ->find($oid)
      ->toArray();
    // 修改inner_order
    $updateInnerOrder = [
      'purchase_time' => date('Y-m-d', strtotime($purchase)),
      'status' => $type === 2 ? ($order['status'] === 3 || $order['base'] === 15 || $order['base'] === 11 ? 3 : 2) : 5,
      'comment' => '',
      'operate_time' => $order['status'] === 3 ? $order['operate_time'] : null,
      'confirm_time' => null,
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    if ($order['base'] === 15 || $order['base'] === 11) {
      $updateInnerOrder['operate_time'] = date('Y-m-d H:i:s');
    }
    // 新增inner_purchase
    $insertInner = [];
    // 获取商品表数据
    $goodsList = GoodsService::getGoodsByCondition([['status', 1, '=']]);
    $goodsList = array_column($goodsList, null, 'id');
    // 返回信息
    $msg = '';
    // 获取库存数量
    foreach ($data as $value) {
      $good = $goodsList[$value['goods_id']];
      if (!($good['price'] * 1)) {
        $msg .= '商品：“'.$good['sale_name'].'” 暂时不能采购<br>';
      }
      $insertInner[] = [
        'inner_order_id' => $oid,
        'house_out_id' => 0,
        'price' => $good['price'],
        'count' => $value['count'],
        'goods_id' => $value['goods_id'],
        'comment' => $value['comment'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    if ($msg && $type === 2) {
      return ['status' => false, 'msg' => $msg];
    }
    self::getModel()->startTrans();
    try {
      // 更新inner_purchase_order
      if ($updateInnerOrder) {
        $res1 = self::getModel()
          ->where('id', '=', $oid)
          ->save($updateInnerOrder);
        if ($res1 === false) {
          throw new \Exception('更新inner_purchase_order失败');
        }
      }
      if ($insertInner) {
        // 删除inner_purchase
        $res2 = self::getDetailModel()
          ->where('inner_order_id', '=', $oid)
          ->delete();
        if ($res2 === false) {
          throw new \Exception('删除inner_purchase失败');
        }
        // 新增inner_purchase
        $res3 = self::getDetailModel()->insertAll($insertInner);
        if ($res3 === false) {
          throw new \Exception('新增inner_purchase失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  /*
   * 内部采购审批通过
   */
  public static function checkInner($orderId, $check, $comment)
  {
    // 修改inner_purchase_order
    $updateInnerOrder = [];
    // 修改store_house
    $updateStore = [];
    // 新增store_house
    $addStore = [];
    // 修改house
    $updateHouse = [];
    // 新增house_out
    $addHouseOut = [];

    // 获取订单
    $order = self::getModel()
      ->find($orderId)
      ->toArray();
    // 获取详情
    $innerList = self::getDetailModel()
      ->where('inner_order_id', '=', $orderId)
      ->select()
      ->toArray();
    // 获取商品表数据
    $goodsList = GoodsService::getGoodsByCondition([['status', 1, '=']]);
    $goodsList = array_column($goodsList, null, 'id');
    // 获取门店实时数量
    $storeList = StoreService::getInstance()->getDataByCondition([['goods_id', 0, '<>'], ['base', $order['base'], '=']]);
    $storeList = array_column($storeList, null, 'goods_id');
    // 获取总部实时数量
    $houseList = HouseService::getInstance()->getHouseJoinGoods();
    $houseList = array_column($houseList, null, 'goods_id');
    // 获取保存分类
    $categoryList = [];
    $storeCat = CategoryService::getInstance()->getCategoryByCondition([['base', $order['base'], '=']]);
    $storeCat = array_column($storeCat, 'id', 'category_name');
    $houseCat = CategoryService::getInstance()->getCategoryByCondition([['base', 0, '=']]);
    $houseCat = array_column($houseCat, 'category_name', 'id');
    foreach ($houseCat as $ck => $cv) {
      if (isset($storeCat[$cv])) {
        $categoryList[$ck] = $storeCat[$cv];
      }
    }
    // 返回信息
    $msg = '';
    // 通过
    if ($check) {
      // 运营通过（改状态）
      if ($order['status'] === 2){
        $updateInnerOrder = [
          'status' => 3,
          'comment' => '',
          'operate_time' => date('Y-m-d H:i:s'),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      // 仓管通过（改状态，入库，仓库出库）
      } elseif ($order['status'] === 3) {
        $updateInnerOrder = [
          'status' => 1,
          'comment' => '',
          'confirm_time' =>date('Y-m-d H:i:s'),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
        foreach ($innerList as $value) {
          $good = $goodsList[$value['goods_id']];
          if (!($good['price'] * 1)) {
            $msg .= '商品：“'.$good['sale_name'].'” 暂时不能采购<br>';
            continue;
          }
          if (!isset($houseList[$value['goods_id']]) || $value['count'] > $houseList[$value['goods_id']]['count']) {
            $msg .= '商品：“'.$good['sale_name'].'” 库存不足<br>';
            continue;
          }
          if (!isset($categoryList[$good['category_id']])) {
            $msg .= '门店暂无：“'.$good['sale_name'].'” 所指定的分类<br>';
            continue;
          }
          // 门店仓库是否已有
          if (isset($storeList[$value['goods_id']])) {
            // 修改store_house
            $store = $storeList[$value['goods_id']];
            $count = $store['count'] + $value['count'];
            $total_amount = $store['total_amount'] + ($value['count'] * $value['price']);
            $updateStore[] = [
              'id' => $store['id'],
              'count' => $count,
              'total_amount' => $total_amount,
              'price' => $count ? round($total_amount/$count, 2) : 0,
              'last_update_time' => date('Y-m-d H:i:s')
            ];
          } else {
            // 新增store_house
            $addStore[] = [
              'goods_id' => $value['goods_id'],
              'category_id' => $categoryList[$good['category_id']],
              'name' => $good['sale_name'],
              'price' => $value['price'],
              'count' => $value['count'],
              'total_amount' => $value['count'] * $value['price'],
              'base' => $order['base'],
              'unit' => $good['unit'],
              'status' => 1,
              'insert_time' => date('Y-m-d H:i:s'),
              'last_update_time' => date('Y-m-d H:i:s')
            ];
          }
          // 修改总部仓库数据
          $house = $houseList[$value['goods_id']];
          $count = $house['count'] - $value['count'];
          $updateHouse[] = [
            'id' => $house['id'],
            'count' => $count,
            'total_amount' => round($count * $house['price'], 2),
            'last_update_time' => date('Y-m-d H:i:s')
          ];
          // 新增售出数据
          $addHouseOut[] = [
            'goods_id' => $value['goods_id'],
            'sell_number' => $order['sell_number'],
            'price' => $house['price'],
            'count' => $value['count'],
            'sell_price' => $value['price'],
            'base' => $order['base'],
            'comment' => $value['comment'],
            'type' => 2,
            'process' => $house['process'],
            'sale_time' => $order['purchase_time'],
            'status' => 1,
            'insert_time' => date('Y-m-d H:i:s'),
            'last_update_time' => date('Y-m-d H:i:s')
          ];
        }
      }
    // 驳回
    } else {
      $updateInnerOrder = [
        'status' => 4,
        'comment' => $comment,
        'operate_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    if ($msg) {
      return ['status' => false, 'msg' => $msg];
    }
    self::getModel()->startTrans();
    try {
      // 新增inner_purchase_order
      if ($updateInnerOrder) {
        $res = self::getModel()
          ->where('id', '=', $orderId)
          ->save($updateInnerOrder);
        if ($res === false) {
          throw new \Exception('修改inner_purchase_order失败');
        }
      }
      // 修改store_house
      if ($updateStore) {
        $res2 = StoreService::getModel()
          ->saveAll($updateStore);
        if ($res2 === false) {
          throw new \Exception('修改store_house失败');
        }
      }
      // 新增store_house
      if ($addStore) {
        $res3 = StoreService::getModel()->insertAll($addStore);
        if ($res3 === false) {
          throw new \Exception('新增store_house失败');
        }
      }
      // 更新house表
      if ($updateHouse) {
        $res4 = HouseService::getModel()
          ->saveAll($updateHouse);
        if ($res4 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 新增house_out
      if ($addHouseOut) {
        foreach ($addHouseOut as $v) {
          $res5 = HouseOutService::getModel()
            ->insertGetId($v);
          if ($res5 === false) {
            throw new \Exception('新增house_in_order失败');
          }
          $res6 = self::getDetailModel()
            ->where('inner_order_id', '=', $orderId)
            ->where('goods_id', '=', $v['goods_id'])
            ->save(['house_out_id' => $res5, 'last_update_time' => date('Y-m-d H:i:s')]);
          if ($res6 === false) {
            throw new \Exception('新增inner_purchase失败');
          }
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 删除审批通过的数据
   */
  public static function deleteStoreInner($id) {
    $order = InnerPurchaseService::getModel()
      ->find($id)
      ->toArray();
    // 修改inner_purchase
    $updateInner = [
      'status' => 0,
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 修改store_house
    $updateStore = [];
    // 修改house
    $updateHouse = [];
    // 修改inner_purchase_order
    $updateInnerOrder = [
      'status' => 0,
      'last_update_time' => date('Y-m-d H:i:s')
    ];

    // 仓管删除
    if ($order['status'] === 1) {
      // 获取订单数据
      $conditions[] = ['i.inner_order_id', $id, '='];
      $inner = InnerPurchaseService::getInstance()->getInnerJoinGoods($conditions);
      // 获取门店实时数量
      $storeList = StoreService::getInstance()->getDataByCondition([['goods_id', 0, '<>'], ['base', $order['base'], '=']]);
      $storeList = array_column($storeList, null, 'goods_id');
      // 获取总部实时数量
      $houseList = HouseService::getInstance()->getHouseJoinGoods();
      $houseList = array_column($houseList, null, 'goods_id');
      // 获取售出数据
      $houseOutList = HouseOutService::getInstance()->getHouseOutJoinGoods([['h.sell_number', $order['sell_number'], '='], ['h.status', 1,'=']]);
      $houseOut = array_column($houseOutList,'id');
      foreach ($inner as $value) {
        if (!isset($storeList[$value['goods_id']])) {
          return ['status' => false, 'msg' => '记录有误，删除失败'];
        }
        $store = $storeList[$value['goods_id']];
        if ($store['count'] - $value['count'] < 0) {
          $msg = '‘'.$store['name'].'’门店内库存不足，删除失败';
          return ['status' => false, 'msg' => $msg];
        }
        // 修改store_house
        $count = $store['count'] - $value['count'];
        $total_amount = $store['total_amount'] - ($value['count'] * $value['price']);
        $updateStore[] = [
          'id' => $store['id'],
          'count' => $count,
          'total_amount' => $total_amount,
          'price' => $count ? round($total_amount/$count, 2) : 0,
          'last_update_time' => date('Y-m-d')
        ];
        // 修改总部仓库数据
        $house = $houseList[$value['goods_id']];
        $count = $house['count'] + $value['count'];
        $updateHouse[] = [
          'id' => $house['id'],
          'count' => $count,
          'total_amount' => round($count * $house['price'], 2),
          'last_update_time' => date('Y-m-d')
        ];
      }
    }
    self::getModel()->startTrans();
    try {
      // 修改inner_purchase_order
      if ($updateInnerOrder) {
        $res = self::getModel()
          ->where('id', '=', $id)
          ->save($updateInnerOrder);
        if ($res === false) {
          throw new \Exception('修改inner_purchase_order失败');
        }
      }
      // 修改inner_purchase
      if ($updateInner) {
        $res1 = self::getDetailModel()
          ->where('inner_order_id', '=', $id)
          ->save($updateInner);
        if ($res === false) {
          throw new \Exception('修改inner_purchase失败');
        }
      }
      // 修改store_house
      if ($updateStore) {
        $res2 = StoreService::getModel()
          ->saveAll($updateStore);
        if ($res2 === false) {
          throw new \Exception('修改store_house失败');
        }
      }
      // 修改house
      if ($updateHouse) {
        $res4 = HouseService::getModel()
          ->saveAll($updateHouse);
        if ($res4 === false) {
          throw new \Exception('修改house失败');
        }
      }
      // 删除house_out
      if (isset($order['sell_number'])) {
        $res5 = HouseOutService::getModel()
          ->where('sell_number', '=', $order['sell_number'])
          ->save($updateInner);
        if ($res5 === false) {
          throw new \Exception('修改house_out失败');
        }
      }

      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 门店内部采购新增
   */
  public static function createMultiInner($data) {
    $base = intval($data['base']);
    $purchase = $data['purchase'];
    $type = $data['type'];
    $data = $data['data'];
    // 新增到inner_purchase
    $insertInner = [];
    // 采购单号
    $cond = [
      ['insert_time', date('Y-m-d'), '>=']
    ];
    $inner = InnerPurchaseService::getModel()->getDataByCondition($cond);
    $arr = array_unique(array_column($inner, 'sell_number'));
    $num = str_pad(count($arr) + 1, 3, '0',STR_PAD_LEFT);
    $sellNumber = 'DD'.date('Ymd').$num;
    // 新增到inner_purchase_order
    $insertInnerOrder = [
      'sell_number' => $sellNumber,
      'base' => $base,
      'purchase_time' => date('Y-m-d', strtotime($purchase)),
      'status' => $type === 2 ? ($base === 15 || $base === 11 ? 3 : 2) : 5,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    if ($base === 15 || $base === 11) {
      $insertInnerOrder['operate_time'] = date('Y-m-d H:i:s');
    }
    // 获取商品表数据
    $goodsList = GoodsService::getGoodsByCondition([['status', 1, '=']]);
    $goodsList = array_column($goodsList, null, 'id');
    // 返回信息
    $msg = '';
    foreach ($data as $value) {
      $good = $goodsList[$value['goods_id']];
      if (!($good['price'] * 1)) {
        $msg .= '商品：“'.$good['sale_name'].'” 暂时不能采购<br>';
      }
      $insertInner[] = [
        'inner_order_id' => '',
        'house_out_id' => 0,
        'price' => $good['price'],
        'count' => $value['count'],
        'goods_id' => $value['goods_id'],
        'comment' => $value['comment'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    if ($msg && $type === 2) {
      return ['status' => false, 'msg' => $msg];
    }
    self::getModel()->startTrans();
    try {
      // 新增inner_purchase_order
      if ($insertInnerOrder) {
        $res1 = self::getModel()
          ->insertGetId($insertInnerOrder);
        if ($res1 === false) {
          throw new \Exception('新增inner_purchase_order失败');
        }
      }
      // 新增inner_purchase
      if ($insertInner) {
        foreach ($insertInner as &$v) {
          $v['inner_order_id'] = $res1;
        }
        $res = self::getDetailModel()->insertAll($insertInner);
        if (!$res) {
          throw new \Exception('新增inner_purchase失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 关联出仓订单
   */
  public static function getInnerJoinHouseOut($conditions = []) {
    $db = Db::name('inner_purchase_order')
      ->alias('o')
      ->field('o.*,u.basename,u.address')
      ->join('inner_purchase i', 'o.id = i.inner_order_id', 'LEFT')
      ->join('house_out ho', 'ho.id = i.house_out_id', 'LEFT')
      ->join('user u', 'u.base = o.base', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $db = $db->where($field, $op, $value);
    }
    return $db
      ->order('o.id', 'DESC')
      ->select()
      ->toArray();
  }

  /*
   * 查询inner与order关联数量
   */
  public function getConnectCount($orderIds) {
    $db = Db::name('inner_purchase_order')
      ->alias('a')
      ->field('a.id, count(a.id) AS num')
      ->join('inner_purchase b', 'b.inner_order_id = a.id', 'LEFT')
      ->where('b.status', '=', 1)
      ->where('a.id', 'IN', $orderIds)
      ->group('a.id')
      ->select()
      ->toArray();
    return $db;
  }
}